import React, { Component } from 'react'
import store from '../../../redux'
import Api from '../../../config/api'
import axios from 'axios'
import Com from '../../../common/common'
import styles from './sass/custom-account-manage.scss'

import Table from 'antd/lib/table'
import Button from 'antd/lib/button'

import Navbar from '../../../Component/navbar'
import Spin from 'antd/lib/spin'
import Icon from 'antd/lib/icon'
import Input from 'antd/lib/input'
import Select from 'antd/lib/select'
import DatePicker from 'antd/lib/date-picker'
import Form from 'antd/lib/form'
import message from 'antd/lib/message'
import Modal from 'antd/lib/modal'
import Popconfirm from 'antd/lib/popconfirm'
import Checkbox from 'antd/lib/checkbox'


import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

const antIcon = <Icon type="loading" style={{ fontSize: 24, marginTop: 200 }} spin />;
const Option = Select.Option;
const FormItem = Form.Item;
const confirm = Modal.confirm;
const { TextArea } = Input;

let oper = null;

const validateNumber = (rule, value, callback) => {
    if (!value) {
        callback()
    }
    else {
        let reg = /^\d*$/g;
        if (reg.test(value)) {
            callback()
        }
        else {
            callback('必须是数字')
        }
    }
}

class OperBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            startDate: '',
            endDate: '',
            startMonent: null,
            endMoment: null,
            SmsUserTypeEnum: [{ index: '', desc: '全部' }],
            SmsUserChargeTypeEnum: [{ index: '', desc: '全部' }],
            SmsUserStatusEnum: [{ index: '', desc: '全部' }],
            SmsUserRechargeTypeEnum: [],
            SmsUserAuditTypeEnum: [],
            showAddModal: false,
            canChangePassword: false
        }
    }
    componentDidMount() {
        this.getSelect();
    }
    async getSelect() {
        await Com.getSelection.call(this, 'SmsUserTypeEnum', 'SmsUserTypeEnum');
        await Com.getSelection.call(this, 'SmsUserChargeTypeEnum', 'SmsUserChargeTypeEnum');
        await Com.getSelection.call(this, 'SmsUserStatusEnum', 'SmsUserStatusEnum');
        await Com.getSelection.call(this, 'SmsUserRechargeTypeEnum', 'SmsUserRechargeTypeEnum', false);
        await Com.getSelection.call(this, 'SmsUserAuditTypeEnum', 'SmsUserAuditTypeEnum', false);
        this.search();
    }
    getTime(type, moment, time) {
        if (type === 'start') {
            this.setState({
                startDate: time,
                startMoment: moment
            })
        }
        else {
            this.setState({
                endDate: time,
                endMoment: moment
            })
        }
    }
    disabledstartTime(current) {
        if (this.state.endMoment) {
            return current > this.state.endMoment
        }
        else {
            return false
        }
    }
    disabledendTime(current) {
        if (this.state.startMoment) {
            return current < this.state.startMoment
        }
        else {
            return false
        }
    }
    search() {
        let obj;
        if (this.accountInput) {
            obj = {
                account: this.accountInput.input.value,
                type: this.typeInput.rcSelect.state.value[0],
                chargeType: this.chargeTypeInput.rcSelect.state.value[0],
                status: this.statusInput.rcSelect.state.value[0],
                startTime: this.state.startDate,
                endTime: this.state.endDate
            }
        }
        else {
            obj = {
                account: '',
                type: '',
                chargeType: '',
                status: '',
                startTime: '',
                endTime: ''
            }
        }
        this.props.search(obj, this.state.SmsUserTypeEnum, this.state.SmsUserChargeTypeEnum, this.state.SmsUserStatusEnum, this.state.SmsUserRechargeTypeEnum, this.state.SmsUserAuditTypeEnum)
    }
    showAddModal() {
        this.setState({
            showAddModal: true
        })
        this.props.form.setFieldsInitialValue({
            type: this.state.SmsUserTypeEnum[1].index,
            chargeType: this.state.SmsUserChargeTypeEnum[1].index,
            auditType: this.state.SmsUserAuditTypeEnum[0].index
        })
    }
    handleCancel() {
        this.setState({
            showAddModal: false
        })
    }
    handleSure(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let data = JSON.parse(JSON.stringify(values))
                data.chargeType = parseInt(data.chargeType, 10)
                data.remindValue = data.remindValue ? parseInt(data.remindValue, 10) : '';
                data.type = parseInt(data.type, 10)
                data.dayCount = parseInt(data.dayCount, 10);
                data.hourCount = parseInt(data.hourCount, 10);
                data.minuteCount = parseInt(data.minuteCount, 10);
                axios.post(Api['addUser'], data).then(res => {
                    if (res) {
                        this.search();
                        this.props.form.resetFields()
                        message.success('提交成功')
                        this.setState({
                            showAddModal: false
                        })
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            }
        });
    }
    changePassword(e) {
        this.setState({
            canChangePassword: e.target.checked
        })
        if (!e.target.checked) {
            this.props.form.setFieldsValue({
                password: ''
            })
        }
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        const formItemLayout2 = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 3 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        return (
            <Navbar ref={(item) => { oper = item }}>
                <Form layout="inline">
                    <FormItem label="账号"><Input ref={(input) => { this.accountInput = input }} /></FormItem>
                    <FormItem label="类型" >
                        <Select defaultValue='' ref={(input) => { this.typeInput = input }}>
                            {this.state.SmsUserTypeEnum.map((item, index) => {
                                return <Option key={index} value={item.index}>{item.desc}</Option>
                            })}
                        </Select>
                    </FormItem>
                    <FormItem label="付费类型" >
                        <Select defaultValue='' ref={(input) => { this.chargeTypeInput = input }}>
                            {this.state.SmsUserChargeTypeEnum.map((item, index) => {
                                return <Option key={index} value={item.index}>{item.desc}</Option>
                            })}
                        </Select>
                    </FormItem>
                    <FormItem label="状态">
                        <Select defaultValue='' ref={(input) => { this.statusInput = input }}>
                            {this.state.SmsUserStatusEnum.map((item, index) => {
                                return <Option key={index} value={item.index}>{item.desc}</Option>
                            })}
                        </Select>
                    </FormItem>
                    <FormItem label="开始时间">
                        <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledstartTime.bind(this)} onChange={this.getTime.bind(this, 'start')} />
                    </FormItem>
                    <FormItem label="结束时间">
                        <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledendTime.bind(this)} onChange={this.getTime.bind(this, 'end')} />
                    </FormItem>
                    <FormItem>
                        <Button type="primary" icon="search" onClick={this.search.bind(this)}>查询</Button>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" icon="plus" onClick={this.showAddModal.bind(this)}>添加</Button>
                    </FormItem>
                </Form>
                <Modal width={800} visible={this.state.showAddModal} onCancel={this.handleCancel.bind(this)} title="新增" footer={[
                    <Button key="sure" type="primary" onClick={this.handleSure.bind(this)}>确定</Button>,
                    <Button key="cancel" type="danger" onClick={this.handleCancel.bind(this)}>取消</Button>
                ]} >
                    <div>
                        <div className={styles['form-input-box']}>
                            <FormItem label="用户账号" {...formItemLayout}>
                                {getFieldDecorator('account', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ required: true, message: '请输入账号' }, { max: 20, message: '20位以内' }, Com.validateSpace] })(<Input />)}
                            </FormItem>
                            <FormItem label="账号类型" {...formItemLayout}>
                                {getFieldDecorator('type', { validateTrigger: 'onBlur', rules: [{ required: true, message: '必选' }] })(<Select>
                                    {this.state.SmsUserTypeEnum.map((item, index) => { if (item.index || item.index === 0) { return <Option value={item.index} key={index}>{item.desc}</Option> } else { return null } })}
                                </Select>
                                )}
                            </FormItem>
                            <FormItem label="客户姓名" {...formItemLayout}>
                                {getFieldDecorator('name', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ max: 10, message: '10位以内' }] })(<Input />)}
                            </FormItem>
                            <FormItem label="联系电话" {...formItemLayout}>
                                {getFieldDecorator('phone', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ len: 11, message: '请输入11位电话号码' }, { validator: validateNumber, message: '纯数字' }] })(<Input />)}
                            </FormItem>
                            <FormItem label="联系邮箱" {...formItemLayout}>
                                {getFieldDecorator('email', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ max: 50, message: '50位以内' }, { pattern: /^.+@.+\..+$/, message: '请输入正确的邮箱' }] })(<Input />)}
                            </FormItem>
                            <FormItem label="提醒阈值" {...formItemLayout}>
                                {getFieldDecorator('remindValue', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ validator: validateNumber, message: '纯数字' }] })(<Input />)}
                            </FormItem>
                            <FormItem label="小时条数" {...formItemLayout}>
                                {getFieldDecorator('hourCount', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ max: 4, message: '不能超过9999条' }, { validator: validateNumber, message: '纯数字' }] })(<Input />)}
                            </FormItem>
                            <FormItem label="审核类型" {...formItemLayout}>
                                {getFieldDecorator('auditType', { validateTrigger: 'onBlur', rules: [{ required: true, message: '必选' }] })(<Select >
                                    {this.state.SmsUserAuditTypeEnum.map((item, index) => { if (item.index || item.index === 0) { return <Option value={item.index} key={index}>{item.desc}</Option> } else { return null } })}
                                </Select>
                                )}
                            </FormItem>
                        </div>
                        <div className={styles['form-input-box']}>
                            <FormItem label="密码" {...formItemLayout}>
                                {getFieldDecorator('password', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ max: 50, message: '不超过50位' }] })(<Input type="password" disabled={!this.state.canChangePassword} placeholder={this.state.canChangePassword ? '' : "自动生成"} />)}
                                <Checkbox style={{ marginLeft: '10px' }} onChange={this.changePassword.bind(this)}>修改</Checkbox>
                            </FormItem>
                            <FormItem label="扩展码" {...formItemLayout}>
                                {getFieldDecorator('extendCode', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ required: true, message: '请输入扩展码' }, { validator: validateNumber, message: '纯数字' }, { len: 3, message: '扩展码只能是3位' }, Com.validateSpace] })(<Input />)}
                            </FormItem>
                            <FormItem label="付款类型" {...formItemLayout}>
                                {getFieldDecorator('chargeType', { rules: [{ required: true, message: '必选' }] })(<Select >
                                    {this.state.SmsUserChargeTypeEnum.map((item, index) => { if (item.index || item.index === 0) { return <Option value={item.index} key={index}>{item.desc}</Option> } else { return null } })}
                                </Select>
                                )}
                            </FormItem>
                            <FormItem label="公司名称" {...formItemLayout}>
                                {getFieldDecorator('companyName', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ max: 50, message: '50位以内' }] })(<Input />)}
                            </FormItem>
                            <FormItem label="余额提醒号码" {...formItemLayout}>
                                {getFieldDecorator('remindPhone', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ len: 11, message: '请输入11位电话号码' }, { validator: validateNumber, message: '纯数字' }] })(<Input />)}
                            </FormItem>
                            <FormItem label="分钟条数" {...formItemLayout}>
                                {getFieldDecorator('minuteCount', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ max: 4, message: '不能超过9999条' }, { validator: validateNumber, message: '纯数字' }] })(<Input />)}
                            </FormItem>
                            <FormItem label="天条数" {...formItemLayout}>
                                {getFieldDecorator('dayCount', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ max: 4, message: '不能超过9999条' }, { validator: validateNumber, message: '纯数字' }] })(<Input />)}
                            </FormItem>
                        </div>
                        <div style={{ clear: 'both' }}></div>
                    </div>
                    <div>
                        <FormItem label="上行地址" {...formItemLayout2}>
                            {getFieldDecorator('receiveUrl', { validateTrigger: 'onBlur', rules: [{ max: 512, message: '512位以内' }, { pattern: /^(https|http):\/\/.+/, message: 'url格式错误,http://或https://开头' }] })(<Input />)}
                        </FormItem>
                        <FormItem label="报备IP" {...formItemLayout2}>
                            {getFieldDecorator('ip', { validateFirst: true, rules: [{ max: 255, message: '255位以内' }] })(<TextArea placeholder="多个以英文逗号隔开" rows={2} />)}
                        </FormItem>
                    </div>
                </Modal>
            </Navbar>
        )
    }
}

const ValidateOperbar = Form.create()(OperBar);

class Table1 extends Component {
    constructor(props) {
        super(props)
        this.state = {
            dataNum: 0,
            tableHeight: 300,
            tableData: this.props.tableData,
            showEditModal: false,
            showRechargeModal: false,
            SmsUserTypeEnum: [],
            SmsUserChargeTypeEnum: [],
            SmsUserStatusEnum: [],
            SmsUserRechargeTypeEnum: [],
            SmsUserAuditTypeEnum: [],
            nowRowId: 0,
            rechargeRow: [],
            currentPage: 1,
            password: '无权限查看'
        }
    }
    componentWillMount() {
        this.setState({
            SmsUserTypeEnum: this.props.selectData[0],
            SmsUserChargeTypeEnum: this.props.selectData[1],
            SmsUserStatusEnum: this.props.selectData[2],
            SmsUserRechargeTypeEnum: this.props.selectData[3],
            SmsUserAuditTypeEnum: this.props.selectData[4]
        })
    }
    componentDidMount() {
        setTimeout(() => {
            let operbarHeight = oper.box.offsetHeight + 10 + 10;
            this.setState({
                tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
            })
            this.unscribe = store.subscribe(this.fullTable.bind(this))
        }, 100)
    }
    componentWillReceiveProps(nextprops, s) {
        this.setState({
            tableData: nextprops.tableData,
            dataNum: nextprops.dataNum,
            currntPage: nextprops.currentPage,
            SmsUserTypeEnum: nextprops.selectData[0],
            SmsUserChargeTypeEnum: nextprops.selectData[1],
            SmsUserStatusEnum: nextprops.selectData[2],
            SmsUserRechargeTypeEnum: nextprops.selectData[3],
            SmsUserAuditTypeEnum: nextprops.selectData[4]
        })
    }
    componentWillUnmount() {
        this.unscribe()
    }
    fullTable() {
        let operbarHeight = oper.box.offsetHeight + 10 + 10;
        this.setState({
            tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
        })
    }
    editModalShow(record) {
        this.setState({
            showEditModal: true,
            nowRowId: record.id
        })
        this.props.form.setFieldsInitialValue({
            account: record.account,
            type: record.type,
            chargeType: record.chargeType,
            extendCode: record.extendCode,
            name: record.name,
            companyName: record.companyName,
            phone: record.phone,
            email: record.email,
            remindPhone: record.remindPhone,
            remindValue: record.remindValue,
            ip: record.ip,
            auditType: record.auditType,
            receiveUrl: record.receiveUrl,
            dayCount: record.dayCount.toString(),
            hourCount: record.hourCount.toString(),
            minuteCount: record.minuteCount.toString()
        })
    }
    editCancel() {
        this.setState({
            showEditModal: false
        })
        this.props.form.resetFields()
    }
    editSure(e) {
        e.preventDefault();
        this.props.form.validateFields(['account', 'chargeType', 'companyName', 'email', 'extendCode', 'ip', 'name', 'phone', 'remindPhone', 'remindValue', 'type', 'auditType', 'receiveUrl', 'dayCount', 'hourCount', 'minuteCount'], (err, values) => {
            if (!err) {
                let data = JSON.parse(JSON.stringify(values))
                data.chargeType = parseInt(data.chargeType, 10)
                data.remindValue = parseInt(data.remindValue, 10)
                data.type = parseInt(data.type, 10);
                data.dayCount = parseInt(data.dayCount, 10);
                data.hourCount = parseInt(data.hourCount, 10);
                data.minuteCount = parseInt(data.minuteCount, 10);
                data.id = this.state.nowRowId;
                axios.post(Api['updateUser'], data).then(res => {
                    if (res) {
                        this.props.search();
                        this.props.form.resetFields()
                        message.success('提交成功')
                        this.setState({
                            showEditModal: false
                        })
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            }
        });
    }
    showRecharge(record) {
        this.setState({
            showRechargeModal: true,
            rechargeRow: record
        })
        this.props.form.setFieldsInitialValue({
            account: record.account,
            smsNum: record.smsNum,
            flag: this.state.SmsUserRechargeTypeEnum[0].index

        })
    }
    handleRechargeSure(e) {
        e.preventDefault();
        this.props.form.validateFields(['value', 'flag', 'description'], (err, values) => {
            if (!err) {
                let data = JSON.parse(JSON.stringify(values))
                let subFlag = false;
                if (data.flag === 2) {
                    if (parseInt(this.state.rechargeRow.smsNum, 10) - parseInt(data.value, 10) < 0) {
                        message.error('退款后余额不能为负')
                    }
                    else {
                        subFlag = true
                    }
                }
                else {
                    subFlag = true
                }
                if (subFlag) {
                    let data1 = {}
                    data1.smsNum = parseInt(data.value, 10);
                    data1.id = this.state.rechargeRow.id;
                    data1.account = this.state.rechargeRow.account;
                    data1.beforeNum = this.state.rechargeRow.smsNum;
                    data1.type = data.flag;
                    data1.description = data.description;
                    axios.post(Api['addRemindValue'], data1).then(res => {
                        if(res){
                            this.props.search();
                            this.props.form.resetFields()
                            message.success('提交成功')
                            this.setState({
                                showRechargeModal: false
                            })
                        }
                    }).catch(function (error) {
                        console.log(error)
                    })
                }
            }
        });
    }
    handleRechargeCancel() {
        this.setState({
            showRechargeModal: false
        })
    }
    showPassword(record) {
        let that = this;
        confirm({
            title: '重置',
            content: '您确定要重置' + record.account + '的密码吗？',
            okText: '重置',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                axios.post(Api['updatePassword'] + '?id=' + record.id).then(res => {
                    if(res){
                        that.props.search();
                        message.success('重置成功')
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            },
            onCancel() { },
        });
    }
    changeStatus(record) {
        this.props.changeStatus(record)
    }
    deleteRow(record) {
        this.props.deleteRow(record)
    }
    validateCharge(rule, value, callback) {
        if (parseInt(value, 10) === 0) {
            callback('条数不能为0')
        }
        else if (parseInt(value, 10) > 1000000) {
            callback('条数不能超过1000000')
        }
        else {
            callback()
        }
    }
    seePassword(record) {
        axios.post(Api['showPassword'] + '?id=' + record.id).then((res) => {
            if(res){
                this.setState({
                    password: res.data
                })
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        const formItemLayout2 = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 3 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        const columns = [
            { title: '账号', dataIndex: 'account', key: '2', width: 220 },
            { title: '业务名称', dataIndex: 'companyName', key: '2', width: 200 },
            { title: '账号类型', dataIndex: 'type1', key: '4', width: 100 },
            {
                title: '密码', key: '10', width: 80, render: (record) => {
                    return (
                        <Popconfirm overlayClassName='no-cancel-pop' placement="top" title={this.state.password}>
                            <a onClick={this.seePassword.bind(this, record)}>查看</a>
                        </Popconfirm>
                    )
                }
            },
            { title: '付款类型', dataIndex: 'chargeType1', key: '5', width: 100 },
            { title: '余额（条）', dataIndex: 'smsNum', key: '7', width: 120 },
            { title: '扩展码', dataIndex: 'extendCode', key: '8', width: 80 },
            { title: '审核类型', dataIndex: 'auditType1', key: '16', width: 100 },
            {
                title: '状态', key: '9', width: 100, render: (record) => {
                    return <span style={{ color: record.status === 1 ? 'green' : 'red' }}>{record.status1}</span>
                }
            },
            { title: '开户时间', dataIndex: 'createTime', key: '13' },
            {
                title: '操作',
                fixed: 'right',
                key: '14',
                width: 320,
                render: (record) => {
                    return (
                        <div>
                            <a onClick={this.editModalShow.bind(this, record)}>编辑</a>
                            <a onClick={this.showRecharge.bind(this, record)} style={{ marginLeft: '10px ' }}>充值/退款</a>
                            <a onClick={this.showPassword.bind(this, record)} style={{ marginLeft: '10px ' }}>重置密码</a>
                            <a onClick={this.changeStatus.bind(this, record)} style={{ marginLeft: '10px ' }}>{record.status === 1 ? '禁用' : '启用'}</a>
                            <a onClick={this.deleteRow.bind(this, record)} style={{ marginLeft: '10px ' }}>删除</a>
                        </div>
                    )
                }
            },
        ];
        return (
            <div className="common-table">
                <Table title={(data) => { return '客户账号列表' }} columns={columns} dataSource={this.state.tableData} pagination={{
                    onChange: this.props.changePage,
                    onShowSizeChange: this.props.changePageSize,
                    defaultPageSize: 20,
                    pageSizeOptions: ['20', '50', '100'],
                    showSizeChanger: true,
                    showQuickJumper: true,
                    current: this.state.currntPage,
                    total: this.state.dataNum,
                    showTotal: total => `共 ${total} 条数据`
                }} scroll={{ x: 1530, y: this.state.tableHeight }}></Table>
                <Modal width={800} visible={this.state.showEditModal} onCancel={this.editCancel.bind(this)} title="编辑" footer={[
                    <Button key="sure" type="primary" onClick={this.editSure.bind(this)}>确定</Button>,
                    <Button key="cancel" type="danger" onClick={this.editCancel.bind(this)}>取消</Button>
                ]} >
                    <div>
                        <div className={styles['form-input-box']}>
                            <FormItem label="用户账号" {...formItemLayout}>
                                {getFieldDecorator('account', { validateFirst: true, rules: [{ required: true, message: '请输入账号' }, { max: 20, message: '20位以内' }, Com.validateSpace] })(<Input disabled />)}
                            </FormItem>
                            <FormItem label="账号类型" {...formItemLayout}>
                                {getFieldDecorator('type', { validateTrigger: 'onBlur', rules: [{ required: true, message: '必选' }] })(<Select>
                                    {this.state.SmsUserTypeEnum.map((item, index) => { if (item.index || item.index === 0) { return <Option value={item.index} key={index}>{item.desc}</Option> } else { return null } })}
                                </Select>
                                )}
                            </FormItem>
                            <FormItem label="客户姓名" {...formItemLayout}>
                                {getFieldDecorator('name', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ max: 10, message: '10位以内' }] })(<Input />)}
                            </FormItem>
                            <FormItem label="联系电话" {...formItemLayout}>
                                {getFieldDecorator('phone', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ len: 11, message: '请输入11位电话号码' }, { validator: validateNumber, message: '纯数字' }] })(<Input />)}
                            </FormItem>
                            <FormItem label="余额提醒号码" {...formItemLayout}>
                                {getFieldDecorator('remindPhone', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ len: 11, message: '请输入11位电话号码' }, { validator: validateNumber, message: '纯数字' }] })(<Input />)}
                            </FormItem>
                            <FormItem label="分钟条数" {...formItemLayout}>
                                {getFieldDecorator('minuteCount', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ max: 4, message: '不能超过9999条' }, { validator: validateNumber, message: '纯数字' }] })(<Input />)}
                            </FormItem>
                            <FormItem label="天条数" {...formItemLayout}>
                                {getFieldDecorator('dayCount', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ max: 4, message: '不能超过9999条' }, { validator: validateNumber, message: '纯数字' }] })(<Input />)}
                            </FormItem>
                        </div>
                        <div className={styles['form-input-box']}>
                            <FormItem label="扩展码" {...formItemLayout}>
                                {getFieldDecorator('extendCode', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ required: true, message: '请输入扩展码' }, { validator: validateNumber, message: '纯数字' }, { len: 3, message: '扩展码只能是3位' }, Com.validateSpace] })(<Input />)}
                            </FormItem>
                            <FormItem label="付款类型" {...formItemLayout}>
                                {getFieldDecorator('chargeType', { validateTrigger: 'onBlur', rules: [{ required: true, message: '必选' }] })(<Select >
                                    {this.state.SmsUserChargeTypeEnum.map((item, index) => { if (item.index || item.index === 0) { return <Option value={item.index} key={index}>{item.desc}</Option> } else { return null } })}
                                </Select>
                                )}
                            </FormItem>
                            <FormItem label="公司名称" {...formItemLayout}>
                                {getFieldDecorator('companyName', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ max: 50, message: '50位以内' }] })(<Input />)}
                            </FormItem>
                            <FormItem label="联系邮箱" {...formItemLayout}>
                                {getFieldDecorator('email', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ max: 50, message: '50位以内' }, { pattern: /^.+@.+\..+$/, message: '请输入正确的邮箱' }] })(<Input />)}
                            </FormItem>
                            <FormItem label="提醒阈值" {...formItemLayout}>
                                {getFieldDecorator('remindValue', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ validator: validateNumber, message: '纯数字' }] })(<Input />)}
                            </FormItem>
                            <FormItem label="小时条数" {...formItemLayout}>
                                {getFieldDecorator('hourCount', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ max: 4, message: '不能超过9999条' }, { validator: validateNumber, message: '纯数字' }] })(<Input />)}
                            </FormItem>
                            <FormItem label="审核类型" {...formItemLayout}>
                                {getFieldDecorator('auditType', { validateTrigger: 'onBlur', rules: [{ required: true, message: '必选' }] })(<Select >
                                    {this.state.SmsUserAuditTypeEnum.map((item, index) => { if (item.index || item.index === 0) { return <Option value={item.index} key={index}>{item.desc}</Option> } else { return null } })}
                                </Select>
                                )}
                            </FormItem>
                        </div>
                        <div style={{ clear: 'both' }}></div>
                    </div>
                    <div>
                        <FormItem label="上行地址" {...formItemLayout2}>
                            {getFieldDecorator('receiveUrl', { validateTrigger: 'onBlur', rules: [{ max: 512, message: '512位以内' }, { pattern: /^(https|http):\/\/.+/, message: 'url格式错误,http://或https://开头' }] })(<Input />)}
                        </FormItem>
                        <FormItem label="报备IP" {...formItemLayout2}>
                            {getFieldDecorator('ip', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ max: 255, message: '255位以内' }] })(<TextArea placeholder="多个以英文逗号隔开" rows={2} />)}
                        </FormItem>
                    </div>
                </Modal>
                <Modal visible={this.state.showRechargeModal} onCancel={this.handleRechargeCancel.bind(this)} title="充值/退款" footer={[
                    <Button key="sure" type="primary" onClick={this.handleRechargeSure.bind(this)}>确定</Button>,
                    <Button key="cancel" type="danger" onClick={this.handleRechargeCancel.bind(this)}>取消</Button>
                ]} >
                    <Form className={styles['modal-form-box']}>
                        <FormItem label="用户账号" {...formItemLayout}>
                            {getFieldDecorator('account')(<Input disabled />)}
                        </FormItem>
                        <FormItem label="当前余额" {...formItemLayout}>
                            {getFieldDecorator('smsNum')(<Input disabled />)}
                        </FormItem>
                        <FormItem label="类型" {...formItemLayout}>
                            {getFieldDecorator('flag', { validateTrigger: 'onBlur', rules: [{ required: true, message: '必选' }] })(<Select>
                                {this.state.SmsUserRechargeTypeEnum.map((item, index) => {
                                    return <Option value={item.index} key={index}>{item.desc}</Option>
                                })}
                            </Select>
                            )}
                        </FormItem>
                        <FormItem label="充值/退款条数" {...formItemLayout}>
                            {getFieldDecorator('value', { validateTrigger: 'onBlur', validateFirst: true, rules: [{ required: true, message: '请输入条数' }, { validator: validateNumber, message: '纯数字' }, { validator: this.validateCharge.bind(this) }, Com.validateSpace] })(<Input />)}
                        </FormItem>
                        <FormItem label="备注" {...formItemLayout}>
                            {getFieldDecorator('description', { validateTrigger: 'onBlur', rules: [{ max: 500, message: '500字以内' }] })(<TextArea rows={3} style={{ width: 300 }} />)}
                        </FormItem>
                    </Form>
                </Modal>
            </div >
        )
    }
}

const ValidateTable = Form.create()(Table1);

class Box extends Component {
    constructor(props) {
        super(props)
        this.state = {
            totalNum: 0,
            tableData: [],
            searchParams: {},
            paginationData: {
                current: 1,
                pageNum: 1,
                pageSize: 20
            },
            currentPage: 1,
            SmsUserTypeEnum: [],
            SmsUserChargeTypeEnum: [],
            SmsUserStatusEnum: [],
            SmsUserRechargeTypeEnum: [],
            SmsUserAuditTypeEnum: [],
            loading: true,
        }
    }
    setParams(obj, SmsUserTypeEnum, SmsUserChargeTypeEnum, SmsUserStatusEnum, SmsUserRechargeTypeEnum, SmsUserAuditTypeEnum) {
        let data = JSON.parse(JSON.stringify(obj));
        this.setState({
            searchParams: data,
            SmsUserTypeEnum,
            SmsUserChargeTypeEnum,
            SmsUserStatusEnum,
            SmsUserRechargeTypeEnum,
            SmsUserAuditTypeEnum
        }, () => {
            this.search('btn');
        })
    }
    search(type) {
        let data = JSON.parse(JSON.stringify(this.state.searchParams));
        if (type === 'btn') {
            data.pageNum = 1;
            this.setState({
                currentPage: 1
            })
        } else {
            data.pageNum = this.state.paginationData.pageNum;
        }
        data.pageSize = this.state.paginationData.pageSize;
        this.setState({
            loading: true,
        })
        axios.post(Api['getUserListByParams'], data).then((res) => {
            if(res){
                let data = JSON.parse(JSON.stringify(res.data));
                data.list.forEach((item, index) => {
                    item.key = index;
                    item.type1 = Com.keyToName(this.state.SmsUserTypeEnum, item.type);
                    item.chargeType1 = Com.keyToName(this.state.SmsUserChargeTypeEnum, item.chargeType);
                    item.status1 = Com.keyToName(this.state.SmsUserStatusEnum, item.status);
                    item.auditType1 = Com.keyToName(this.state.SmsUserAuditTypeEnum, item.auditType);

                    if (item.companyName) {
                        item.companyNameAbb = Com.abbrData(item.companyName, 10);
                    }
                    if (item.receiveUrl) {
                        item.receiveUrlAbb = Com.abbrData(item.receiveUrl, 20);
                    }
                })
                this.setState({
                    loading: false,
                    tableData: data.list,
                    totalNum: data.total
                })
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    changePageSize(current, size) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = current;
        pagination.pageSize = size;
        this.setState({
            paginationData: pagination,
            currentPage: current
        }, () => { this.search('pag') })
    }
    changePage(pageNum, pageSize) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = pageNum;
        pagination.pageSize = pageSize;
        this.setState({
            paginationData: pagination,
            currentPage: pageNum
        }, () => { this.search('pag'); })
    }
    deleteRow(record) {
        let that = this;
        confirm({
            title: '删除',
            content: '您确定要删除' + record.account + '吗？',
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                axios.post(Api['deleteUser'] + '?id=' + record.id).then(res => {
                    if(res){
                        that.search();
                        message.success('删除成功')
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            },
            onCancel() { },
        });
    }
    changeStatus(record) {
        let that = this;
        let text = record.status === 1 ? '禁用' : '启用'
        confirm({
            title: text,
            content: '您确定要' + text + record.account + '吗？',
            okText: text,
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                axios.post(Api['changeStatus'] + '?id=' + record.id).then(res=> {
                    if(res){
                        that.search();
                        message.success(text + '成功')
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            },
            onCancel() { },
        });
    }
    render() {
        return (
            <div>
                <ValidateOperbar search={this.setParams.bind(this)} />
                <Spin spinning={this.state.loading} indicator={antIcon}>
                    <ValidateTable
                        search={this.search.bind(this)}
                        tableData={this.state.tableData}
                        dataNum={this.state.totalNum}
                        currentPage={this.state.currentPage}
                        changePageSize={this.changePageSize.bind(this)}
                        changePage={this.changePage.bind(this)}
                        deleteRow={this.deleteRow.bind(this)}
                        changeStatus={this.changeStatus.bind(this)}
                        selectData={[this.state.SmsUserTypeEnum, this.state.SmsUserChargeTypeEnum, this.state.SmsUserStatusEnum, this.state.SmsUserRechargeTypeEnum, this.state.SmsUserAuditTypeEnum]}
                    />
                </Spin>
            </div>
        )
    }
}

export default Box